Repository navigation
feat(rust): observe rust-model solutions natively - #5963
Merged
Merged
Conversation
This was referenced Oct 22, 2026
This was referenced Oct 22, 2026
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #5963 +/- ##
==========================================
+ Coverage 98.40% 98.42% +0.02%
==========================================
Files 363 363
Lines 38745 39034 +289
==========================================
+ Hits 38127 38421 +294
+ Misses 618 613 -5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This was referenced Oct 22, 2026
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
from
October 28, 2026 09:55
73c029c to
879f508
Compare
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
2 times, most recently
from
October 28, 2026 14:11
26c1029 to
63e4b86
Compare
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
2 times, most recently
from
October 29, 2026 08:01
b77ac50 to
52b69b1
Compare
BradyPlanden
marked this pull request as ready for review
October 29, 2026 08:56
Contributor
|
| Project | PyBaMM |
| Branch | stack/08-native-observation |
| Testbed | bare-metal |
🐰 View full continuous benchmarking report in Bencher
⚠️ WARNING: Truncated view!The full continuous benchmarking report exceeds the maximum length allowed on this platform.
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
from
October 29, 2026 17:26
52b69b1 to
b55c69e
Compare
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
from
November 17, 2026 11:24
b55c69e to
b6a75a5
Compare
BradyPlanden
changed the base branch from
stack/07a-rust-ffi-layout
to
stack/07-idaklu-rust-mode
November 30, 2026 11:54
4 tasks done
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
2 times, most recently
from
December 2, 2026 09:22
5699aaa to
0fc2584
Compare
A second reader in build_variable: a model bound with ObserverCache.bind_rust_model reads each segment through native tapes kept on its ObserverCache, with shared-tape variable sets and native sensitivities.
#6056 makes `x.diff(pybamm.t)` work through functions and observables, and pins that observing one raises `ModelError("Must provide a 'y_dot'...")`: observation gives a leaf no state derivatives. A native leaf compiled the derivative regardless and failed only when read, with another message. The native leaf and the native set now refuse a tape reading `y_dot` as they compile, with the error `process` raises, so `Solution.observe` and `Solution.update` fail the same way for either format.
`_sweep_sensitivities` built each parameter's direction as a C-order `(n_states, n_t)` transpose of `dy_dp`, a strided copy that Rust then gathered again into the column-major layout it reads. Gathering the column first and reshaping gives an F-contiguous array, which Rust borrows. Reading the sensitivities of a Rust DFN over 10,000 points, with three parameters, drops from 242 ms to 15 ms for "Voltage [V]", and from 1.58 s to 87 ms for six variables. At the 138 points the solver steps to, it drops from 0.56 ms to 0.19 ms.
Reading Rust solutions natively is how IDAKLUSolver serves Rust models, which no release reaches yet, so it takes no entry. What every backend sees is `Solution.update([...])` now storing a list all or nothing, so the entry records that.
Native observation compiled its leaves on the graph of the CompiledModel a solver had bound to the model's ObserverCache, each leaf lowering afresh. A model no solver bound, as ScipySolver left every model, or a hand-built Solution read through CasADi, as did a VectorField. The _observes_via_compiled_model flag chose which solvers bound. Every Rust model's variables, VectorField components among them, now compile on its RustModelLowering, sharing its memo of lowered symbols, and a leaf reads as many states as its segment stores. ObserverCache keeps only CasADi leaves, and the flag goes. Setting the model up again keeps its leaves; a copy compiles its own. Reading five variables of a ScipySolver SPM solution takes 6 ms rather than 10 ms.
Native leaves were cached on the model's lowering by variable name, and the lowering now outlives a set-up, so a variable given a new expression went on reading the old one. A Solution whose inputs held the model's names in another order replaced the model's lowering, though leaves take their inputs by name, and each such read rebuilt the graph and every leaf. Leaves, shared tapes, time integrals and post-sum tapes are cached by the expression they compile as well as the name. A segment reads through the model's lowering whenever it has the segment's input names, in whatever order. VariableObserver.with_leaves is abstract.
…l's graph A Solution whose inputs were not the model's replaced the model's lowering, dropping its CompiledModel and every compiled variable. It now reads through a lowering of its own, and the model's is used only for its own inputs, in any order, or made when the model has none.
A Solution whose inputs were not the model's made a new lowering for every read and every segment, so each read recompiled every variable. That lowering is now cached on the model's, by the set of input names.
- The single-set num_threads test compared one call with itself; only its pool check could fail, so it keeps that alone. - The dense-grid test's read sat below its tolerance on a chord as well as a cubic; the flags carry the change. It now reads 4097 columns over one span, without a stop at every column. - A first-interval read superseded by the analytic ones goes, and the stepped-current voltage check uses assert_allclose. - ed2422fe2 (a failed set-up keeps the last good one) and 50bbe35eb (other inputs reuse one lowering per set of names) gain the tests that fail without them.
…all matching Codecov found native observation's patch short of the project's coverage. The Solution vector-field test now runs on both formats, so a Rust model's components are read natively, through NativeObserver's with_leaves and the lowering a hand-built Solution's model makes on first read. A hand-built three-segment solution, its middle segment a single knot, is read natively and through CasADi at query times in one segment and in all three. A table test covers when a shared tape reuses a held call.
BradyPlanden
force-pushed
the
stack/08-native-observation
branch
from
December 3, 2026 11:03
0fc2584 to
4cb7407
Compare
martinjrobins
requested changes
Dec 4, 2026
martinjrobins
left a comment
Contributor
There was a problem hiding this comment.
looks great, thanks @BradyPlanden , just minor stuff below
A vector field compiled each component on its own and dropped the time integral a component held, so a component read as its integrand in place of its integral, through CasADi and natively alike. Reading such a variable now raises NotImplementedError on either path.
NativeObserver, SharedOutputs and SharedOutputLeaf, the native sensitivity helpers, and the native build functions now carry type hints. Typing their bodies checks two invariants with casts: a vector field's observer is read only per component, and a post-sum node always has its compiled tape. A tape's inputs are a mapping or the packed vector, as the bindings accept. native_sensitivities, native_postfix_sensitivities and chain_rule_sensitivities have no caller outside the module, so they become private.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Reads variables, and their sensitivities, from a rust-model
IDAKLUSolversolution in Rust.set_upbinds theCompiledModelto the model'sObserverCache(refactor: read solution variables through per-model observer caches #5786).build_variablethen evaluates each variable on a tape compiled into the model's retained graph: one Rust call per segment, cubic-Hermite between time points when the solution stores derivatives.Besides
CompiledModel.graph, a getter it adds to the bindings with its stub, this PR is Python only; the other Rust methods it calls (n_states,ExprGraph.from_expr) are from #5962.ObserverCache:bind_rust_model,native_leaf(a variable's tape, compiled once per model),native_set(several variables on one tape, sharing subexpressions) andpost_sum_leaf.set_updrops the native leaves.observation.pysays.NativeObserver: evaluates raw values (eval_trajectory), Hermite values (eval_trajectory_hermite) and sensitivities. Time integrals add their post-sum sensitivities throughnative_postfix_sensitivities. On anoutput_variablessolve, a variable that is not an output reads its values and sensitivities from the placeholder states, as on the CasADi path.Solution.update([...]):SharedOutputstape and sweeps its sensitivities once per parameter, and each variable reads its rows through aSharedOutputLeaf. A segment with no time points gives empty rows.output_variablessolve) nothing is stored. Before, on CasADi and rust alike, the names before the failing one were rebuilt and kept.update("name")with one string is unchanged.QuickPlotandSolution.get_data_dictbuild all their variables this way.ProcessedVariableTimeIntegral.sum_over_timeis public, andcheck_discrete_timesis a method, for the native path.When native reading applies:
IDAKLUSolver.VectorFieldvariables.VectorFieldvariables are read one by one, not on a shared tape.calculate_sensitivitiesraisesValueError, as onmain.ModelErroras it compiles, the error CasADi'sprocessraises (feat: IDAKLU termination events on time derivatives #6056).On the CasADi path, values are unchanged.
Solution.updatededuplicates its names and stores all or nothing, andQuickPlotandget_data_dictbuild every variable up front.Review on #5732
observation.pykeeps the observer naming from refactor: read solution variables through per-model observer caches #5786 onmain(ObserverCache,VariableObserver), and the class under review is not in this stack.backend[key]is:SharedOutputsholds one result for as many reads as it has leaves, which its docstring states. Each call keeps its own result and a lock guards the held one, so threads reading different solutions while the GIL is released get their own rows.Type of change
New feature, under
## FeaturesinCHANGELOG.md.Key checklist
pre-commit runt_interp;output_variablessolve;updatestoring nothing when one name fails.Rust execution engine stack: proposal #5667, showcase #5732
Each PR builds on the one above it.
Function.create_copykeeps the function's classRegPowerand uniform-grid interpolant lookups matchevaluatepybamm-core: expression graph, typed IR, interpreters, forward-mode ADpybamm-core:CompiledModel, coloured Jacobians, the C ABIpybamm.rustbindings, built into thepybammwheelSymbol.to_rustconvert_to_format = "rust"forScipySolver,AlgebraicSolverand EISpybammsolvers: IDAKLU over the C ABIIDAKLUSolveron rust modelspybamm-core: diffsol DAE solverpybamm.DiffsolSolverInterpolantover input parameters and expressionspybamm.rust's own errors, array-likes, threads and Ctrl-Cpybamm.rust.inspection; every tape derived in one place"rust"as the defaultconvert_to_format